'use strict';

const Controller = require('egg').Controller;


const Alipay = require('alipay-mobile');

// const feiyun = require('../../service/feiyun');

class V1Controller extends Controller {
    async index() {
        this.ctx.body = {
            "result": "无人点餐系统api接口",
            "success": true
        }
    }
    async productList() {
        let result = await this.ctx.model.ProductCate.findAll({
            include: {
                model: this.ctx.model.Product,
                attributes: ["id", "cid", "title", "price", "imgUrl", "sort"]
            },
            order: [
                ['sort', 'DESC'],
                [this.ctx.model.Product, 'sort', 'DESC'],
            ],
        });
        this.ctx.body = {
            "result": result,
            "success": true
        }

    }

    async productContent() {
        let id = this.ctx.request.query.id;
        let result = await this.ctx.model.Product.findAll({
            where: {
                id: id
            }
        })
        if (result.length > 0) {
            this.ctx.body = {
                "result": result,
                "success": true
            }
        } else {
            this.ctx.body = {
                "result": [],
                "success": false
            }
        }

    }
    /*
    增加购物车接口  
      1、判断购物车是否有当前桌号对应的菜品数据
      2、没有的话执行增加
      3、有的话执行修改  让数量加1  
    */
    async addCart() {
        let body = this.ctx.request.body;
        let tableId = body.tableId;
        let productId = body.productId;
        let cartResult = await this.ctx.model.Cart.findAll({
            where: {
                tableId: tableId,
                productId: productId
            }
        })
        if (cartResult.length > 0) {
            this.ctx.model.Cart.update({
                productNum: cartResult[0].productNum + 1
            }, {
                where: {
                    tableId: tableId,
                    productId: productId
                }
            });
        } else {
            await this.ctx.model.Cart.create({
                ...body,
                addTime: this.ctx.service.tools.getUnixTime(),
            });
        }

        this.ctx.body = { "success": 'true', "msg": "增加数据成功" };
    }
    //购物车列表
    async cartList() {
        try {
            let tableId = this.ctx.request.query.tableId;
            let cartResult = await this.ctx.model.Cart.findAll({
                where: {
                    tableId: tableId
                }
            })
            this.ctx.body = { "success": true, "result": cartResult };

        } catch (error) {
            this.ctx.body = { "success": false, "result": [] };
        }

    }
    // 增加购物车数量
    async incCart() {
        let body = this.ctx.request.body;
        let tableId = body.tableId;
        let productId = body.productId;
        let cartResult = await this.ctx.model.Cart.findAll({
            where: {
                tableId: tableId,
                productId: productId
            }
        })
        if (cartResult.length > 0) {
            this.ctx.model.Cart.update({
                productNum: cartResult[0].productNum + 1
            }, {
                where: {
                    tableId: tableId,
                    productId: productId
                }
            });
            this.ctx.body = { "success": true, "msg": "更新成功" };
        } else {
            this.ctx.body = { "success": false, "msg": "更新失败" };
        }



    }
    // 增加减少购物车数量
    async decCart() {
        let body = this.ctx.request.body;
        let tableId = body.tableId;
        let productId = body.productId;
        let cartResult = await this.ctx.model.Cart.findAll({
            where: {
                tableId: tableId,
                productId: productId
            }
        })
        if (cartResult.length > 0) {
            if (cartResult[0].productNum > 1) {
                this.ctx.model.Cart.update({
                    productNum: cartResult[0].productNum - 1
                }, {
                    where: {
                        tableId: tableId,
                        productId: productId
                    }
                });
            } else {
                this.ctx.model.Cart.destroy({
                    where: {
                        tableId: tableId,
                        productId: productId
                    }
                });
            }
            this.ctx.body = { "success": true, "msg": "更新成功" };
        } else {
            this.ctx.body = { "success": false, "msg": "更新失败" };
        }
    }
    //获取购物车总数量
    async cartCount() {
        try {
            let tableId = this.ctx.request.query.tableId;
            //总数量
            let count = await this.ctx.model.Cart.sum(
                "productNum",
                { where: { tableId: tableId } }
            )
            count = count ? count : 0;

            //总价格
            let allPrice = await this.ctx.model.Cart.sum(
                "productPrice",
                { where: { tableId: tableId } }
            )
            allPrice = allPrice ? allPrice : 0;

            this.ctx.body = { "success": true, count: count, allPrice: allPrice };

        } catch (error) {
            this.ctx.body = { "success": false, count: 0 };
        }
    }

    //获取口味信息
    async flavorList() {
        let result = await this.ctx.model.Setting.findAll();
        //少辣，不要葱，打包带走   ["少辣","不要葱"]
        let list = result[0].orderLabel.replace("，", ",").split(",");
        this.ctx.body = { "success": true, result: list };
    }

    //增加修改用户用餐信息
    async addPeopleInfo() {
        let body = this.ctx.request.body;
        let tableId = body.tableId;
        let result = await this.ctx.model.PeopleInfo.findAll({
            where: {
                tableId: tableId,
            }
        })
        if (result.length > 0) {
            await this.ctx.model.PeopleInfo.update(body, {
                where: {
                    tableId: tableId
                }
            })
            this.ctx.body = { "success": true, "msg": "更新成功" };
        } else {
            await this.ctx.model.PeopleInfo.create(body);
            this.ctx.body = { "success": true, "msg": "更新成功" };
        }
    }
    // 获取用户用餐信息
    async getPeopleInfo() {
        try {
            let tableId = this.ctx.request.query.tableId;
            let result = await this.ctx.model.PeopleInfo.findAll({
                where: {
                    tableId: tableId
                }
            })
            if (result.length > 0) {
                this.ctx.body = { "success": true, result: result[0] };
            } else {
                this.ctx.body = { "success": false, result: null };
            }

        } catch (error) {
            this.ctx.body = { "success": false, result: [] };
        }
    }

    /*
    增加订单接口：
        1、获取数据 并解析orderItem
        2、判断当前桌子下面是否有已下单并且未支付的订单，如果有的话更新订单，没有执行增加
        3、清空当前桌子对应的购物车数据
        4、打印小票
    */
    async addOrder() {
        let body = this.ctx.request.body;

        let tableId = body.tableId;
        let pNum = body.pNum;    //用餐人数
        let pMark = body.pMark;  //备注口味信息
        let orderItems = body.orderItems ? JSON.parse(body.orderItems) : [];  //菜品信息
        let orderId = this.service.tools.getOrderId();   ///  //生成orderId
        let totalPrice = body.totalPrice;  //总价格
        let totalNum = body.totalNum;      //总数量        
        let payStatus = 0;   //0表示未支付  1表示已经支付
        let orderStatus = 0; //0表示已 下单并且未支付        1 表示已支付 已完结     2表示取消
        let addTime = this.service.tools.getUnixTime();  //增加日期


        let orderResult = await this.ctx.model.Order.findAll({
            where: {
                tableId: tableId,
                payStatus: 0,
                orderStatus: 0
            }
        })
        if (orderResult.length > 0) {  //合并订单
            await this.ctx.model.Order.update({
                totalPrice: Number(totalPrice) + Number(orderResult[0].totalPrice),
                totalNum: Number(totalNum) + Number(orderResult[0].totalNum),
            }, {
                where: {
                    tableId: tableId,
                    payStatus: 0,
                    orderStatus: 0
                }
            })

            for (let i = 0; i < orderItems.length; i++) {
                await this.ctx.model.OrderItems.create({
                    orderId: orderResult[0].id,
                    tableId: tableId,
                    productId: orderItems[i].productId,
                    productImg: orderItems[i].productImg,
                    productTitle: orderItems[i].productTitle,
                    productPrice: orderItems[i].productPrice,
                    productNum: orderItems[i].productNum,
                    status: 1    /*状态是1  表示已经下厨     状态是2表示退菜*/
                })
            }


        } else {  //增加订单

            //1、增加order表的数据
            let orderCreateResult = await this.ctx.model.Order.create({
                tableId,
                pNum,
                pMark,
                orderId,
                totalPrice,
                totalNum,
                payStatus,
                orderStatus,
                addTime
            })
            console.log(orderCreateResult);
            //2、增加order_item表的数据
            if (orderCreateResult) {
                for (let i = 0; i < orderItems.length; i++) {
                    await this.ctx.model.OrderItems.create({
                        orderId: orderCreateResult.id,
                        tableId: tableId,
                        productId: orderItems[i].productId,
                        productImg: orderItems[i].productImg,
                        productTitle: orderItems[i].productTitle,
                        productPrice: orderItems[i].productPrice,
                        productNum: orderItems[i].productNum,
                        status: 1    /*状态是1  表示已经下厨     状态是2表示退菜*/
                    })
                }
            }

        }

        //清空当前桌子对应的购物车数据
        this.ctx.model.Cart.destroy({
            where: {
                tableId: tableId
            }
        });

        //打印小票
        var orderInfo = this.service.tools.getOrderPrintInfo(totalPrice, pMark, tableId, orderItems);

        // feiyun.print('918502453',orderInfo);


        this.ctx.body = { "success": true, "msg": "增加订单成功" };
    }
    //获取订单信息
    async getOrder() {
        let tableId = this.ctx.request.query.tableId;
        let result = await this.ctx.model.Order.findAll({
            include: {
                model: this.ctx.model.OrderItems
            },
            where: {
                tableId: tableId,
                payStatus: 0,
                orderStatus: 0
            }
        })
        this.ctx.body = {
            "result": result,
            "success": true
        }
    }


    async login() {
        // 获取口味信息
        let result = await this.ctx.model.Setting.findAll();
        //少辣，不要葱，打包带走   ["少辣","不要葱"]
        let list = result[0].orderLabel.replace("，", ",").split(",");

        //生成Jwt Token
        const token = this.app.jwt.sign({ foo: 'bar' }, this.app.config.jwt.secret, {
            expiresIn: 60 * 60 * 2
        });
        this.ctx.body = {
            "success": true,
            "token": token,
            "flavorList": list
        }

    }


    async alipay() {

        //notify_url: 异步通知url
        //app_id: 开放平台 appid
        //appPrivKeyFile: 你的应用私钥
        //alipayPubKeyFile: 蚂蚁金服支付公钥


        const options = {
            app_id: '2017122101048570',
            appPrivKeyFile: "MIIEowIBAAKCAQEA2YqSo7uX27Fdi32MEx2hAmfZUWl19KNovLLEm3P6mlQYkD7+ThVE8468n8meyTBl2QC8YXQVbGANbFdwdcxldDnOUKv7f9VFiaXn+jT0t9hJ00t5HLJ2yY85hMWFhuO+wxIjZdJ82u4dekY7F2T32wC7qIx4dsncPVfCvW4nB8Co6+eVi+PBEkp92HiBk/b4HbjhZxBCe9urbiN9syO5ZlVzAPUDcDvlRVSICv0S9BzWCQPjzxO8sd6jvJ/EFBmbz9VjvFbOkwSoibElY7kShDtAR2Ae/PTzEF2hvOUKVI/hW7T2p7VewgYF1kcPxlLoZJ8Zljxn7EYhMmsfukbPHQIDAQABAoIBAHPUS9XwWaA5ZTSTiZTYDtXoE5c8jvjOVUM78GFRNJsdseKEGAXdX1RLqPVvdiNrqJ8NvEArfgixcBRCznd6eH6VFNxxZj0fgqIS+1yG+9Iz0MM3iWoVQBh8MUUXosw60WSucLiThbVQWdO0N1xyf2JVlpXdDXs6ahEjfGY+k3uVR0No0qIBgwirM2Ofyk3orgBFxXgEbjpoAindpglrqhw2LlMMNb9wwNkjzB/guiYhRu3xOoodstPqcR/FXy0WLRc6W+pxF83E7lPJ22U3DLM2yIc4NQjGxa8Kfkhm0fQUQz5M1akRfk0nj6w8sIjd5XJKgw+Cjosh4EubHVptpyUCgYEA8DzEleQo01hdZqHLeYBghbuEuoFm+N80Xk/7i4Dxlny2R4ZO/sCH3ZURbwcI4kA2WvdScB2Lir9NI10HJNW3xJRjVpumPzfrNxLoYZb+2h0eSS6peIlMAidZyspwGEwLE+jelnMQu8IVbKQ0aTN8tjpKolbpII95Tlq58Ijf8ksCgYEA59CVDkNU+dCufVnLHkOASrd0AGmXMccKeBZfpNlZIdmH9/KBRbXiUec8TWgDwfZg8e//FMCA7r4Y4pj2XZhb+G0M3FfBf2hjKjkqVDEv9+3zYK4zI07ts2WRvkLgY+SvzFYwSEo/U72zka1ocWdDZtiNdXqqAC5DTTc6zIIsozcCgYBPDdAq+v+sPIHPyiIpA2O/3isZLIf0EY8sEenWyEG3oaZh9wJ7tmN/ORSZkpkLytGYMZbBKhfHOphpsK0vI9zrJWFjGKkmWIJghypNIuEOaVKUBnTiI1wNwWE86Ezm0e87SAAnRgoVnxJpw8czbyv0003ICg2BF3V1oUlaq8/17QKBgAD+cvUpsr6Td3wQG3/YuD8ZxESQL1bGTLQxHF3flLNBdITKpGVBH2RMgoSucn2tacL/zW8wWB0t8XtfPocuNQ6+oPR859Z9AxfWQOk1gMgmXAnJFW0MVJaVU+el78Jd46cTo4db0iOwx4lTXgRGdhKF0S10xi/UAvPczcK8uCZHAoGBAN+74UouDYmZaAfzj5O0857ZVHBiXtJ5AasYqbBALZ17EqTjscYcD3nlvWhoX7JtGAyU09fuH23NK6hpi3yk67KUBuJOab+wjjDUIIAveFqjmiaV+Ra727v39d2ide534ikOfz04RDiAUVA43V+a3kdaAXuvTfhF+mczjN3joFtm",
            alipayPubKeyFile: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhb/KlxYfhRE8KRp92MQM8ZB8NVjoM9LYFOnPIuNtcMZVA8ld7ybDP2FiA+QEE7wLGqMImwl1Y4xzkrTLCjHVC8fdR8ZvzZR2I3ZOrARerI9+RbkCfT+7YLv55+A+WTHEyiB+v7PfXVTT28s0CHNLPXMyQD1u8UVEQEpbMSs8hH3pJF55Li7kc5VvJpV3RVO9TXZTVAA5mSp9FvO3u+47IJDgFVLnqqHh6ETL1nHVpxiAY2LGer+RWpVYD8v+We+VWsrfJP7bO0xr2pwizldepo8YNYPgcIAIwd7KiveypL1pA0xWgSjUHzrkVh1j/nSnvJgKSdydU/VRcaVt/Mt8wwIDAQAB",
            // gatewayUrl: "https://openapi.alipay.com/gateway.do"
        }

        const service = new Alipay(options);

        let d = new Date();
        const data = {
            subject: '辣条 标题',
            out_trade_no: '1232423' + d.getTime(),
            total_amount: '0.2'
        }
        const basicParams = {
            return_url: 'https://s.itying.com/',
            notify_url: "https://s.itying.com/api/v1/alipayNotify",
        }
        let result = await service.createWebOrderURL(data, basicParams)
        this.ctx.body = {
            "success": true,
            "message": result,
        }

    }

    //接收阿里给我们post的xml数据
    async alipayNotify() {

        const options = {
            app_id: '2017122101048570',
            appPrivKeyFile: "MIIEowIBAAKCAQEA2YqSo7uX27Fdi32MEx2hAmfZUWl19KNovLLEm3P6mlQYkD7+ThVE8468n8meyTBl2QC8YXQVbGANbFdwdcxldDnOUKv7f9VFiaXn+jT0t9hJ00t5HLJ2yY85hMWFhuO+wxIjZdJ82u4dekY7F2T32wC7qIx4dsncPVfCvW4nB8Co6+eVi+PBEkp92HiBk/b4HbjhZxBCe9urbiN9syO5ZlVzAPUDcDvlRVSICv0S9BzWCQPjzxO8sd6jvJ/EFBmbz9VjvFbOkwSoibElY7kShDtAR2Ae/PTzEF2hvOUKVI/hW7T2p7VewgYF1kcPxlLoZJ8Zljxn7EYhMmsfukbPHQIDAQABAoIBAHPUS9XwWaA5ZTSTiZTYDtXoE5c8jvjOVUM78GFRNJsdseKEGAXdX1RLqPVvdiNrqJ8NvEArfgixcBRCznd6eH6VFNxxZj0fgqIS+1yG+9Iz0MM3iWoVQBh8MUUXosw60WSucLiThbVQWdO0N1xyf2JVlpXdDXs6ahEjfGY+k3uVR0No0qIBgwirM2Ofyk3orgBFxXgEbjpoAindpglrqhw2LlMMNb9wwNkjzB/guiYhRu3xOoodstPqcR/FXy0WLRc6W+pxF83E7lPJ22U3DLM2yIc4NQjGxa8Kfkhm0fQUQz5M1akRfk0nj6w8sIjd5XJKgw+Cjosh4EubHVptpyUCgYEA8DzEleQo01hdZqHLeYBghbuEuoFm+N80Xk/7i4Dxlny2R4ZO/sCH3ZURbwcI4kA2WvdScB2Lir9NI10HJNW3xJRjVpumPzfrNxLoYZb+2h0eSS6peIlMAidZyspwGEwLE+jelnMQu8IVbKQ0aTN8tjpKolbpII95Tlq58Ij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nvJgKSdydU/VRcaVt/Mt8wwIDAQAB",
        }
        const service = new Alipay(options);

        //获取post的xml数据
        const params = this.ctx.request.body;  //注意配置中间件：koa-xml-body

        const result = await service.makeNotifyResponse(params);

        if (result.code == 0) {
            if (params.trade_status == 'TRADE_SUCCESS') {
                console.log(result);
                
                //处理订单
                this.ctx.body = {
                    "success": true,
                    "message": result,
                }
            }
        }
    }

}

module.exports = V1Controller;
